package com.per.mybootall.test.babyOkt;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: yyy
 * Date: 2022/7/8
 * Time: 11:30
 * Description:
 */
@Component
public class test23 {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    UrlInitBean urlInitBean;

    private static volatile ExecutorService threadPoolExecutor;

    private final static int THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1;

    public void sendHttpClient(){
        CopyOnWriteArrayList<String> urlList=urlInitBean.getInclude();
        HttpHeaders header=headerInit();
        getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                while (true){
                    sendClient(urlList,header);
                }
            }
        });
    }


    public void sendClient(List<String> urlList,HttpHeaders httpHeaders){
        urlList.forEach(initUrl->{
            String realUrl=initUrl.substring(0,initUrl.indexOf("?")==-1?initUrl.length():initUrl.indexOf("?"));
            List<String> paramsList= Arrays.asList(initUrl.substring(initUrl.indexOf("?")+1,initUrl.length()).split("&"));
            Map paramsMap=new HashMap();
            paramsList.forEach(paramItem->{
                List param=Arrays.asList(paramItem.split("="));
                if(param.size()==1){
                    paramsMap.put(param.get(0),"");
                }else{
                    paramsMap.put(param.get(0),param.get(1));
                }
            });
            HttpEntity<Map> mapHttpEntity = new HttpEntity<>(paramsMap, httpHeaders);
            ResponseEntity<String> exchange = restTemplate.exchange(realUrl, HttpMethod.GET, mapHttpEntity, String.class);
            System.out.println("返回结果："+JSONObject.toJSONString(exchange));
        });
    }

    public HttpHeaders headerInit(){
        //todo 有时间再改 这里可以替换成数据库配置「我不确定这些配置数据项是否永远有效，换成数据库会更好点，包括上面的urlList，换成中心数据库更好点」
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Accept","*/*");
        httpHeaders.add("Accept-Encoding","gzip, deflate, br");
        httpHeaders.add("Accept-Language","zh-CN,zh;q=0.9");
        httpHeaders.add("Connection","keep-alive");
        httpHeaders.add("Cookie","BIDUPSID=AB343A8DDBB79443EAD3EA9636FDDC69; PSTM=1656465095; BAIDUID=AB343A8DDBB79443575F5229AF616002:FG=1; BD_UPN=12314753; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; BDUSS=I0fjVQaVJ-QWlOck9OeHRhS0gwd0NRcWIxbWNTS3dCVDB3VTBub0Nua0ptZXRpRVFBQUFBJCQAAAAAAAAAAAEAAAAZICxrysfKx7fHt8c0MzU4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkMxGIJDMRiTD; BDUSS_BFESS=I0fjVQaVJ-QWlOck9OeHRhS0gwd0NRcWIxbWNTS3dCVDB3VTBub0Nua0ptZXRpRVFBQUFBJCQAAAAAAAAAAAEAAAAZICxrysfKx7fHt8c0MzU4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkMxGIJDMRiTD; BDSFRCVID_BFESS=SLDOJexroG062-7DvXuRU12Vy2KK0gOTDYrEOwXPsp3LGJLVc8uvEG0PtsaxgF4b1DMtogKKXgOTHw0F_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF_BFESS=tRk8oI0aJDvjDb7GbKTMbtCSbfTJetJyaR3TLKnvWJ5WqR7jD5jHqq0vMPQL3qLDtHc8oqvcbfL5ShbXXMo10nIVeH8DKb5NWGc2VPKE3l02V-bv-fJf5qRDhpAO04RMW23v0h7mWP02sxA45J7cM4IseboJLfT-0bc4KKJxbnLWeIJEjjCajTcQjN_qq-jeHDrKBRbaHJOoDDvHjnocy4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xNjIwMzY1MDJjZGM3YWY4YzBmZDExODYzMDM2ZTZkYmFkM2EyNDdhZTUzMzIwNTkyMzNlM2FjMDU3ZWEzZTdjMWJiZDhhNzM2YWY0ODk0NGIxZDI3NTEwZGQ1MmI0MmQ2MDI0Yw==; BDRCVFR[Ter2S3H5o_D]=mk3SLVN4HKm; BDSVRTM=26; WWW_ST=1657248486330");
        httpHeaders.add("Host","www.baidu.com");
        httpHeaders.add("is_pbs","%E7%99%BE%E5%BA%A6%E5%AE%89%E5%85%A8%E9%AA%8C%E8%AF%81");
        httpHeaders.add("is_referer","https://www.baidu.com/s?wd=%E7%99%BE%E5%BA%A6%E5%AE%89%E5%85%A8%E9%AA%8C%E8%AF%81&rsv_spt=1&rsv_iqid=0xf60f4e6c0036528a&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=88093251_95_hao_pg&rsv_enter=0&rsv_dl=tb&rsv_t=cfbcuVnl9k1g%2BWjgz2oS7k2oHJepjLVjMlUVBwIJF3uD3V9YXzmxrzZqafI6Gl6OjkQTv66Nyl0g&oq=%25E8%2594%25A1%25E5%25BE%2590%25E5%259D%25A4%25E6%2598%25AF%25E5%2593%25AA%25E9%2587%258C%25E7%259A%2584%25E4%25BA%25BA&rsv_btype=t&rsv_pq=bcd43ceb00314cfd&rsv_sug3=9&rsv_sug1=8&rsv_sug7=100&rsv_n=2&rsv_sug2=0&inputT=737&rsv_sug4=737&bs=%E8%94%A1%E5%BE%90%E5%9D%A4%E6%98%AF%E5%93%AA%E9%87%8C%E7%9A%84%E4%BA%BAis_xhr: 1");
        httpHeaders.add("Referer","https://www.baidu.com/s?wd=%E7%99%BE%E5%BA%A6%E5%AE%89%E5%85%A8%E9%AA%8C%E8%AF%81&rsv_spt=1&rsv_iqid=0xf60f4e6c0036528a&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=88093251_95_hao_pg&rsv_enter=0&rsv_dl=tb&rsv_t=cba3AvJGNGJ9Ei4okyXvNWx47VVMglGwxdGKdH8IxA4K0cRzd0%2FVTI4NNJb3N7f5RPybtc04psWD&oq=%25E7%2599%25BE%25E5%25BA%25A6%25E5%25AE%2589%25E5%2585%25A8%25E9%25AA%258C%25E8%25AF%2581&rsv_btype=t&rsv_pq=f43c35890035413c");
        httpHeaders.add("sec-ch-ua","' Not A;Brand';v='99', 'Chromium';v='102', 'Google Chrome';v='102'");
        httpHeaders.add("sec-ch-ua-mobile","?0");
        httpHeaders.add("sec-ch-ua-platform","Windows");
        httpHeaders.add("Sec-Fetch-Dest","empty");
        httpHeaders.add("Sec-Fetch-Mode","cors");
        httpHeaders.add("Sec-Fetch-Site","same-origin");
        httpHeaders.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
        httpHeaders.add("X-Requested-With","XMLHttpRequest");
        return httpHeaders;
    }


    private ExecutorService getThreadPool() {
        if (threadPoolExecutor == null) {
            synchronized (this) {
                if (threadPoolExecutor == null) {
                    threadPoolExecutor = new ThreadPoolExecutor(THREAD_POOL_SIZE,
                            THREAD_POOL_SIZE,
                            0,
                            TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(),
                            new ThreadFactory() {
                                @Override
                                public Thread newThread(Runnable r) {
                                    return new Thread(r, "线程池调用");
                                }
                            },
                            new ThreadPoolExecutor.CallerRunsPolicy());
                }
            }
        }
        return threadPoolExecutor;
    }
}
